package xyz.liut.ee.web

import jakarta.servlet.http.HttpServlet
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse

abstract class BaseServlet : HttpServlet() {

    override fun service(req: HttpServletRequest, resp: HttpServletResponse) {
        resp.allowCors()
        super.service(req, resp)
    }

    override fun doOptions(req: HttpServletRequest, resp: HttpServletResponse) {
        resp.allowOptionsCors()
        super.doOptions(req, resp)
    }

}

abstract class BaseNoDefaultServlet : HttpServlet() {
    override fun service(req: HttpServletRequest, resp: HttpServletResponse) {
        resp.allowCors()
        if(req.getMethod().equals("OPTIONS")){
            doOptions(req, resp)
        }
    }

    override fun doOptions(req: HttpServletRequest, resp: HttpServletResponse) {
        resp.allowOptionsCors()
        super.doOptions(req, resp)
    }
}


/**
 * 允许跨域
 */
private fun HttpServletResponse.allowCors() {
    addHeader("Access-Control-Allow-Origin", "*")
    addHeader("Access-Control-Allow-Credentials", "true")
}

/**
 * 允许跨域 headers
 */
private fun HttpServletResponse.allowOptionsCors() {
    addHeader("Access-Control-Allow-Methods", "GET, DELETE, PATCH, PUT, HEAD, POST, TRACE, OPTIONS")
    addHeader("Access-Control-Allow-Headers", "Content-Type")
}

